package com.oceansoft.core.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oceansoft.core.common.util.IDGenerator;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


@Controller
public class BaseController {
	private static final Log logger = LogFactory
			.getLog(BaseController.class);


	protected static String uploadTemp(HttpServletRequest request,HttpServletResponse response,
									   CommonsMultipartFile mfile) {
		// 生成存放目录
		String storeFilePath = request.getSession().getServletContext().getRealPath("/")+"ExcelTemp\\"+ IDGenerator.getUid()+".xls";
		File desfile = new File(storeFilePath);
		InputStream in = null;
		FileOutputStream out = null;
		try {
			in = mfile.getInputStream();
			out = new FileOutputStream(desfile);
			FileCopyUtils.copy(in, out);
		} catch (FileNotFoundException e) {
			logger.error("文件未找到", e);
		} catch (IOException e) {
			logger.error(e);
		} finally {
			try {
				in.close();
				out.flush();
				out.close();
			} catch (IOException e) {
				logger.error(e);
			}
		}
		return storeFilePath;
	}
	protected static void deleteTemp(String filePath) {
		File file = new File(filePath);
		if(file.isFile())
		{
			file.delete();
		}
	}


	/**
	 * 文件下载
	 *
	 * @param response
	 * @param fileName
	 * @param file
	 */
	public void downloadFile(HttpServletResponse response, String fileName,
							 File file) {
		response.reset();
		InputStream is = null;
		OutputStream os = null;
		try {
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment; filename="
					+ new String((fileName).getBytes("GBK"), "ISO-8859-1"));
			is = new FileInputStream(file);
			os = new BufferedOutputStream(response.getOutputStream());
			byte[] bytes = new byte[4096];
			int len;
			while ((len = is.read(bytes)) != -1) {
				os.write(bytes, 0, len);
			}
		} catch (Exception ex) {

		} finally {
			try {
				os.flush();
				os.close();
				is.close();
			} catch (IOException e) {

			}
		}
	}

	public static Map<String, String> doubleExcelMap(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<?> enu = request.getParameterNames();
		String value="";
		while (enu.hasMoreElements()) {
			String paraName = (String) enu.nextElement();
			value= request.getParameter(paraName).replaceAll("'", "");
			if(null!=value&&!"".equals(value))
			{
				try {
					paraName=new String(paraName.getBytes("ISO-8859-1"),"UTF-8");
					value=new String(value.getBytes("ISO-8859-1"),"UTF-8");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			map.put(paraName,value);
		}

		return map;
	}
	// 将request信息封装
	public static Map<String, String> excelMap(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<?> enu = request.getParameterNames();
		String value="";
		while (enu.hasMoreElements()) {
			String paraName = (String) enu.nextElement();
			value= request.getParameter(paraName).replaceAll("'", "");
			if(null!=value&&!"".equals(value))
			{
				try {
					value=new String(value.getBytes("ISO-8859-1"),"UTF-8");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			map.put(paraName,value);
		}

		return map;
	}

	protected static void flushResponse(HttpServletResponse response,
										String responseContent) {

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.write(responseContent);
		} catch (IOException e) {
			logger.error(e);
		} finally {
			writer.flush();
			writer.close();
		}

	}

	protected static void flushResponseMsg(HttpServletResponse response,
										   boolean success, String msg) {

		JSONObject jsonObj = new JSONObject();
		jsonObj.put("success", success);
		jsonObj.put("msg", msg);
		String jsonStr = jsonObj.toString();
		flushResponse(response, jsonStr);
	}
}
